import { useUserStore } from "@/store/modules/user";
import axios from "axios";
import { showNotify } from "@nutui/nutui";
import { AxiosRequestConfig } from "axios";

const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: 10000,
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => config,
  async (error) => {
    showNotify.danger("请求失败，请稍后重试");
    throw error;
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 如果是 arraybuffer 类型的响应，直接返回
    if (response.config.responseType === "arraybuffer") {
      return response;
    }

    const { data } = response;

    if (data.code === 401) {
      useUserStore().resetAuth();
    }

    if (data.code !== 0) {
      // showNotify.danger(data.msg);
      return Promise.reject(data);
    }

    return response;
  },
  (error) => {
    // showNotify.danger("响应失败，请稍后重试");
    return Promise.reject(error);
  }
);

const request = async <T>(config: AxiosRequestConfig & { noLogin?: boolean } = { noLogin: false }) => {
  const userStore = useUserStore();
  config.headers = config.headers || {};
  // 测试环境需要加上租户id，正式环境因为ng会自动配置，所以不需要
  if (import.meta.env.DEV) {
    config.headers["tenant-id"] = import.meta.env.VITE_TENANT_ID;
  }
  if (!config.noLogin) {
    await userStore.checkLocalAuth();
    config.headers["Authorization"] = `Bearer ${userStore.auth.accessToken}`;
  }
  return (await instance<T>(config)).data;
};

export default request;
